package ru.bragnikita.utils.logexplorer.web;

import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import java.io.File;

/**
 * @author Nikita.Brazhnikov
 */
@FacesValidator("DirectoryValidator")
public class DirectoryExistsValidator implements Validator {

	private static final Logger logger = LoggerFactory.getLogger(DirectoryExistsValidator.class);

	@Override
	public void validate(FacesContext facesContext, UIComponent uiComponent, Object o) throws ValidatorException {
		logger.debug("Validating directory {}", ObjectUtils.toString(o, "null"));
		String messageText = null;
		if (ObjectUtils.toString(o, "").isEmpty()) {
			messageText = "Directory name is empty";
		} else {
			String path = o.toString();
			if (!new File(path).exists())
				messageText = "Directory not found";
			else if (!new File(path).isDirectory())
				messageText = "Specified path is not directory path";

		}
		if (messageText != null) {
			throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, messageText, messageText));
		}
	}

}
